package com.shenhaofeng.rxcache;

import android.content.SharedPreferences;

import com.shenhaofeng.rxcache.source.CacheSource;

import rx.Observable;
import rx.Subscriber;

/**
 * Created by haofeng on 2016/9/25.
 */

class LoadCacheOnSubscribe<T> implements Observable.OnSubscribe<T> {

    private CacheSource<T>[] mCacheSources;
    private String mKey;

    public LoadCacheOnSubscribe(String key, CacheSource<T>[] cacheSources) {
        this.mCacheSources = cacheSources;
        this.mKey = key;
    }


    @Override
    public void call(Subscriber<? super T> subscriber) {
        try {
            subscriber.onStart();
            for (int i = 0; i < mCacheSources.length; i++) {
                T data = mCacheSources[i].get(mKey);
                if (data != null) {
                    subscriber.onNext(data);
                    subscriber.onCompleted();
                    return;
                }
            }
            subscriber.onCompleted();
        } catch (Throwable e) {
            subscriber.onError(e);
        }

    }
}
